package com.llc.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.llc.common.constant.SeckillConstant;
import com.llc.common.exception.BizException;
import com.llc.common.to.mq.SeckillOrderTo;
import com.llc.common.utils.R;
import com.llc.common.vo.MemberResponseVo;
import com.llc.gulimall.seckill.feign.CouponFeignService;
import com.llc.gulimall.seckill.feign.ProductFeignService;
import com.llc.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.llc.gulimall.seckill.service.SeckillService;
import com.llc.gulimall.seckill.to.SeckillSkuRedisTo;
import com.llc.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.llc.gulimall.seckill.vo.SeckillSkuVo;
import com.llc.gulimall.seckill.vo.SkuInfoVo;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.BEncoderStream;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author llc
 * @Description
 * @Version
 * @date 2022/2/19 0:56
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    //redisson 信号量前缀
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";  //后面接随机码


    @Override
    public void uploadSeckillSkuLatest3Days() {
        // 1.远程调用gulimall-coupon服务查询最近三天秒杀活动和商品
        R session = couponFeignService.getLatest3DaySession();
        if (session.getCode() != 0) {
            log.error("gulimall-seckill调用gulimall-coupon获取最近三天秒杀活动失败");
            //throw new BizException(BizCodeEnum.CALL_FEIGN_SERVICE_FAILED, "上架秒杀活动信息失败");
        }
        List<SeckillSessionsWithSkus> sessionData = (List<SeckillSessionsWithSkus>) session.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
        });
        //将数据缓存到redis
        if (CollectionUtils.isEmpty(sessionData)) {
        }
        // 3.保存活动场次信息
        log.info(">>>保存秒杀活动场次信息");
        saveSessionInfos(sessionData);
        // 4.保存活动商品和库存信息
        log.info(">>>>>>保存秒杀活动商品和库存信息");
        saveSessionSkuInfos(sessionData);
    }


    //查询当前场次的秒杀信息

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //确定当前时间属于那个场次
        Long time = new Date().getTime();

        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        //log.info("keys:"+keys);
        for (String key : keys) {
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            Long start = Long.parseLong(s[0]);
            //log.info("start"+start);
            Long end = Long.parseLong(s[1]);
            //log.info("end"+end);
            //log.info("time"+time);
            if (time >= start && time <= end) {
                //获取秒杀场次所需要所有商品信息
                //log.info("有符合的场次");
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                //log.info("range:"+range);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = hashOps.multiGet(range);
                if (list != null) {
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        //SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                        SeckillSkuRedisTo redis = JSON.parseObject((String) item, SeckillSkuRedisTo.class);
                        //redis.setRandomCode(null); 秒杀开始需要随机码
                        return redis;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }

        return null;
    }


    /**
     * @param skuId
     * @return com.llc.gulimall.seckill.to.SeckillSkuRedisTo
     * @author llc
     * @description 提供当前商品是否参与秒杀的远程服务
     * @date 2022/2/20 15:59
     */

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //所有找到需要秒杀的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            //正则表达式来处理
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                //6-4
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo skuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    //随机码要隐藏
                    Long startTime = skuRedisTo.getStartTime();
                    Long endTime = skuRedisTo.getEndTime();
                    Long current = new Date().getTime();
                    if (current >= startTime && current <= endTime) {

                    } else {
                        skuRedisTo.setRandomCode(null);
                    }
                    return skuRedisTo;
                }
            }
        }
        return null;
    }

    /**
     * @param killId
     * @param key
     * @param num
     * @return java.lang.String
     * @author llc
     * @description 秒杀  结合消息队列来实现
     * @date 2022/2/20 22:56
     */
    //TODO 商品过期时间
    //TODO 秒杀后续流程 简化了收货地址等计算
    @Override
    public String kill(String killId, String key, Integer num) {
        MemberResponseVo respVo = LoginUserInterceptor.loginUser.get();
        //获取当前商品的消息信息
        log.info("到kill函数");
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {

            return null;
        } else {
            SeckillSkuRedisTo redis = JSON.parseObject(json, SeckillSkuRedisTo.class);
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            Long time = new Date().getTime();
            Long ttl = endTime - startTime; //单位为ms
            //1 校验时间
            if (time >= startTime && time <= endTime) {
                //2 校验随机码
                String randomCode = redis.getRandomCode();
                String skuId = redis.getPromotionSessionId() + "_" + redis.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)) {
                    //3 验证购物数量
                    if (num <= redis.getSeckillLimit()) {
                        //验证这个人是否购买过  秒杀成功就占位 userID_SessionId_skuId
                        //SETNX
                        String redisKey = respVo.getId() + "_" + skuId;
                        //超时时间
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        log.info("aboolean:"+aBoolean);
                        if (aBoolean) {
                            //如果占位成功说明 没有购买过
                            //分布式信号量减操作
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            try {

                                boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                log.info("b:"+b);
                                if(b){
                                    //秒杀成功
                                    //快速下单  发送mq消息 10ms
                                    String timeId = IdWorker.getTimeId();
                                    SeckillOrderTo orderTo = new SeckillOrderTo();
                                    orderTo.setOrderSn(timeId);
                                    orderTo.setMemberId(respVo.getId());
                                    orderTo.setNum(num);
                                    orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                    orderTo.setSkuId(redis.getSkuId());
                                    orderTo.setSeckillPrice(redis.getSeckillPrice());
                                    log.info("发出订单消息");
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
                                    log.info(("订单消息发送成功"));
                                    return timeId;
                                }else {
                                    return null;
                                }
                            } catch (InterruptedException e){
                                return null;
                            }
                        } else {
                            //说明已经买过了
                            return null;
                        }

                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }
        return null;
    }


    //保存活动场次信息
    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessions) {
        for (SeckillSessionsWithSkus session : sessions) {
            Date startTime = session.getStartTime();
            Date endTime = session.getEndTime();
            //时间比较
            // 前后缀组成key
            String suffix = startTime.getTime() + "_" + endTime.getTime();
            String key = SESSIONS_CACHE_PREFIX + suffix;
            // 避免重复上架
            if (redisTemplate.hasKey(key)) {
                continue;
            }
            // 值为当前场次下所有skuid，有的sku在多个场次中都有，所以保存成 场次id_skuid
            List<String> sessionSkus = session.getRelationSkus().stream().map(sku -> session.getId() + "_" + sku.getSkuId()).collect(Collectors.toList());
            //缓存活动信息
            redisTemplate.opsForList().leftPushAll(key, sessionSkus);
            // 设置过期时间，活动结束自动过期,ms
            redisTemplate.expireAt(key, endTime);
        }
    }

    //保存商品信息

    /**
     * 提前锁定好库存。
     * 保存每个场次里的sku详细信息以及库存(信号量形式)
     * <p>
     * hash结构 ：seckill:sku: 场次id_skuid->skuinfo
     * <p>
     * hash结构多用于保存对象信息，键值设置过期时间
     * 我们这里保存 场次:sku信息，又因为不同场次结束时间不同，所以不能对同一个键下不同属性设置不同过期时间
     */
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessions) {

        sessions.stream().forEach(session -> {
            //准备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                //设置随机码
                String token = UUID.randomUUID().toString().replace("-", "");

                if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString())) {
                    //缓存商品
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //sku基本数据  调用远程服务来查询
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        //成功的
                        SkuInfoVo info = (SkuInfoVo) skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfo(info);
                    }

                    //sku秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, redisTo);
                    //设置上当前的秒杀时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());


                    redisTo.setRandomCode(token);


                    String jsonString = JSON.toJSONString(redisTo);
                    log.info("商品信息保存完成" + jsonString);
                    ops.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(), jsonString);
                    // 设置分布式信号量  前缀+随机码 限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
            });
        });
    }
}
